using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace Q.Framework.Extension
{
    public static class ControlExtension
    {
        public static List<T> FindControlsByType<T>(this Control control, Boolean breakOnFirstFound = false) where T : Control
        {
            List<T> list = new List<T>();
            foreach (Control c in control.Controls)
            {
                if (c.GetType() == typeof(T) || c.GetType().IsSubclassOf(typeof(T)))
                {
                    list.Add(c as T);
                    if (breakOnFirstFound)
                        break;
                }
                else
                    FindControlsByTypeRecursive<T>(c, ref list);
            }
            return list;
        }

        private static void FindControlsByTypeRecursive<T>(Control root, ref List<T> list, Boolean breakOnFirstFound = false) where T : Control
        {
            if (root.Controls.Count != 0)
            {
                foreach (Control c in root.Controls)
                {
                    if (c.GetType() == typeof(T) || c.GetType().IsSubclassOf(typeof(T)))
                    {
                        list.Add(c as T);
                        if (breakOnFirstFound)
                            break;
                    }
                    else if (c.HasControls())
                        FindControlsByTypeRecursive<T>(c, ref list);
                }
            }
        }

        public static T FindControlRecursive<T>(this Control container, string ID) where T : Control
        {
            if (container.ID == ID)
                return container as T;

            foreach (Control ctrl in container.Controls)
            {
                T foundCtrl = FindControlRecursive<T>(ctrl, ID);
                if (foundCtrl != null)
                    return foundCtrl;
            }
            return null;
        }
    }
}